PythonNote
=Python Learning Note= Language Free learning materials * Dive Into Python 2.x * Dive Into Python 3.x * Learn Python The Hard Way, 3rd Edition Main Method #!/usr/bin/python import os import sys def main(): pass if __name__ "__main__": exit(main()) Statement if statement * if * if else * if elif else loop statement * for i in range(... * for else (else clause is executed when for exhausts its option, see more) * while boolean with statement with open("x.txt") as f: data = f.read() #do something with data class controlled_execution: def __enter__(self): set things up return thing def __exit__(self, type, value, traceback): tear things down with controlled_execution() as thing: some code Decorators Pass by Object Reference Generator Polymorphism Lambda f = lambda x: x**2 + 2*x - 5 # f = function(x):return x**2 + 2*x - 5 lambda x: x % 3 0, 2, 3, 4, 5, 6, 7, 8, 9 mult3 = filter(lambda x: x % 3 0, 2, 3, 4, 5, 6, 7, 8, 9) def filterfunc(x): return x % 3 0 mult3 = filter(filterfunc, 2, 3, 4, 5, 6, 7, 8, 9) mult3 = for x in [1, 2, 3, 4, 5, 6, 7, 8, 9 if x % 3 0] def transform(n): return lambda x: x + n f = transform(3) Reference python=lambda-why Usage Regular Expression #list directory, split ...file-name in file-name names = os.listdir(sys.argv1) pattern = "(\.*\)" for line in names: m = re.search(pattern, line) subs = re.split(pattern, line) print(line) for sub in subs: if sub != None and len(sub) > 0: print(" %s" % (sub)) Reference * http://www.pythonregex.com/ * http://www.tutorialspoint.com/python/python_reg_expressions.htm File IO #read user raw input str = raw_input("Enter your input: "); # read user input, calculate python-express/statement into result as input # Enter your input: for x in range(2,10,2) # Recieved input is : 20, 30, 40 str = input("Enter your input: "); #!/usr/bin/python # Open a file # write and binary mode fo = open("/tmp/foo.txt", "wb") fo.write( "some string\n"); # Close opend file fo.close() Database Sqlite3 #import the sqlite3 module import sqlite3 #open or create database db = sqlite3.connect("used.db") #sql statement cmd = "select user_id, user_name from ..." #query for row in db.execute(cmd): userId = row0 userName = row1 ... #close db db.close() MySQL sudo apt-get install python-mysqldb #!/usr/bin/python import _mysql import sys try: con = _mysql.connect('localhost', 'testuser', 'test623', 'testdb') con.query("SELECT VERSION()") result = con.use_result() print "MySQL version: %s" % \ result.fetch_row()0 except _mysql.Error, e: print "Error %d: %s" % (e.args0, e.args1) sys.exit(1) finally: if con: con.close() #!/usr/bin/python #http://pypi.python.org/pypi/MySQL-python/ import MySQLdb db = MySQLdb.connect(host="localhost", # your host, usually localhost user="john", # your username passwd="megajonhy", # your password db="jonhydb") # name of the data base # you must create a Cursor object. It will let # you execute all the query you need cur = db.cursor() # Use all the SQL you like cur.execute("SELECT * FROM YOUR_TABLE_NAME") # print all the first cell of all the rows for row in cur.fetchall() : print row0 * Python MySQL Database Access click Spreadsheet xlwt import xlwt wb = Workbook() ws = wb.add_sheet("Sheet1") ws.write(rowNum, colNum, cellValue) #... wb.save("file-path-name.xls") Template Engine Django from django.template import Template, Context from django.conf import settings settings.configure() t = Template('My name is .') c = Context({'my_name': 'Daryl Spitzer'}) t.render© Jinja2 Testing Framework unittest import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def test_shuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) # should raise an exception for an immutable sequence self.assertRaises(TypeError, random.shuffle, (1,2,3)) def test_choice(self): element = random.choice(self.seq) self.assertTrue(element in self.seq) def test_sample(self): with self.assertRaises(ValueError): random.sample(self.seq, 20) for element in random.sample(self.seq, 5): self.assertTrue(element in self.seq) if __name__ '__main__': unittest.main() Reference click